<template>
	<view>
		<view class="navtop">
			<view class="left" @click="phones">
				<image src="../../static/userSide/back22.png" mode="widthFix"></image>
				<view>
					拨打电话
				</view>
			</view>
			<view class="left" @click="place">
				<image src="../../static/userSide/back11.png" mode="widthFix"></image>
				<view>
					马上下单
				</view>
			</view>
		</view>
		<view class="" style="position: relative;">
			<scroll-view class="scroll-view" scroll-y="true" style="width: 92vw;margin: 30rpx auto;"
				:style="{height:height+'rpx'}" :scroll-top="scrollTop" @scroll='scroll' :lower-threshold='200'
				:upper-threshold='heights' @scrolltoupper='scrolltoupper' @scrolltolower='scrolltolower'
				@refresherpulling="onPulling" @refresherrefresh="onRefresh" @refresherrestore="onRestore"
				:refresher-enabled='true' refresher-default-style='none' :refresher-triggered="triggered">
				<view class="pos" style="position: relative;background-color: #fff;">
					<view class="tips color_fff size_12 align_c" :class="{ 'show':ajax.loading }" @tap="getHistoryMsg">
						{{ajax.loadText}}</view>
					<view class="box-1" id="list-box">
						<view class="talk-list">
							<view v-for="(item,index) in talkList" :key="index" :id="`msg-${item.id}`">
								<view class="item flex_col" :class=" item.type == 1 ? 'push':'pull' ">
									<image :src="item.pic" mode="aspectFill" class="pic"></image>
									<view class="content">{{item.content}}</view>
								</view>
							</view>
						</view>
						<view class="liubai" style="height: 280rpx;">

						</view>
					</view>
				</view>
			</scroll-view>
			<view class="" v-if="newsshow" @click="ceshi()"
				style="position: absolute;padding: 15rpx 30rpx;background-color: #2691E6;border-radius: 100rpx;font-size: 24rpx;color: #fff;left: 20rpx; bottom:30rpx;display: flex;align-items: center;">
				有10条新消息<image src="../../static/userSide/chevronsdown.png"
					style="width: 30rpx;height: 30rpx;margin-left: 15rpx;"></image>
			</view>
		</view>

		<view class="box-2">
			<view class="flex_col">
				<view class="jia" @click="shows=!shows">
					<u-icon name="plus" size='15' color='#999'></u-icon>
				</view>
				<view class="flex_grow">
					<input style="width: 60vw; background-color:#F4F4F4 ;" type="text" class="content" v-model="content"
						placeholder="请输入您想表达的内容..." placeholder-style="color:#DDD;" :cursor-spacing="6">
				</view>
				<button class="send" @click="sends">发送</button>
			</view>
			<view class="bott" v-if="shows">
				<view class="left" @click="order">
					<view class="img">
						<image src="../../static/userSide/ckdd22.png" mode="widthFix"></image>
					</view>
					<view class="">
						查看订单
					</view>
				</view>
				<view class="left" @click="phone">
					<view class="img">
						<image src="../../static/userSide/lxkf22.png" mode="widthFix"></image>
					</view>
					<view class="">
						联系客服
					</view>
				</view>
			</view>
		</view>

	</view>
</template>

<script>
import {
  chatEliminate,
  chatSlist, getUserInfo
} from '../../api/api.js'
	import UniSocket from '@/js_sdk/UpYou-websocket/uni.socket'
	export default {
		data() {
			return {
				shows: false,
				triggered: false,
				talkList: [],
				charId: 0,
				ajax: {
					rows: 10, //每页数量
					page: 0, //页码
					flag: true, // 请求开关
					loading: true, // 加载中
					loadText: '正在获取消息'
				},
				content: '',
				height: 0,
				socket: null,
				userid: null,
				scrollTop: 0,
				newsshow: false,
				heights: 0,

        info:{},
        list:[]
			}
		},
		mounted() {
			this.$nextTick(() => {
				console.log(this.talkList)
				if (this.talkList.length != 0) {
					this.getHistoryMsg();
				} else {
					setTimeout(() => {
						this.ajax.loading = false;
					}, 300);
				}
			});
			uni.getSystemInfo({
				success: res => {
					this.windowHeight = res.windowHeight;
					console.log("屏幕高度", res.windowHeight) //res.windowHeight是返回的屏幕高度
					this.height = res.windowHeight * 2 - 450
					this.heights = this.height - 500
					console.log(this.heights);
				}
			});
		},
		onUnload() {
			//结束心跳
			this.socket.killApp();
			//关闭socket
			this.socket.close();
		},
		onLoad(option) {
			let that = this
			this.userid = option.id //接收者id
			this.status = option.status
			console.log(this.status)
			let data = {
				userIds: option.id,
				userid: this.$store.state.userInfo.wxInfo.uid
			}
      getUserInfo(option.id).then(res=>{
        this.info = res.data.info
        this.list = res.data.evaluation
      })

			chatEliminate(data).then(res => {
				console.log(res)
			})
			//连接
			this.socket = new UniSocket({
				url: 'wss://youdexinli.dongdiankeji.cn/websocket/message/' + this.$store.state.userInfo.wxInfo.uid + "/" + this.userid + "/" +  option.orderid +"/" +this.status,
				//url: 'ws://192.168.0.137:9095/websocket/message/' + this.$store.state.userInfo.wxInfo.uid + "/" + this.userid + "/" +  option.orderid +"/1",
				heartRate: 2000
			})

			this.socket.on("error", function(daata) {
				uni.showToast({
					title: daata,
					icon: 'none'
				})
			})

			this.socket.on("chatInformation", function(daata) {
				if (daata.length > 0) {
					that.charId = daata[0].chatId.split(',')[1]
					for (var i = 0; i < daata.length; i++) {
						daata[i].createTime = that.dateFormat(daata[i].createTime);
						that.talkList.push(daata[i])
					}
					console.log(that.talkList)
				}

			})
			this.socket.on(this.$store.state.userInfo.wxInfo.uid, function(data) {
				if (data.id == that.userid) {
					if(data.orderId == null){
						let datas = {
							"id": new Date().getTime(),
							"content": data.msg,
							"type": 0,
							"pic": option.ava
						}
						that.talkList.push(datas);
						console.log("收到消息了：", data);
					}
				}

			})
		},
		methods: {
			dateFormat(value) {
				let date = new Date(value);
				let y = date.getFullYear();
				let MM = date.getMonth() + 1;
				MM = MM < 10 ? ('0' + MM) : MM;
				let d = date.getDate();
				d = d < 10 ? ('0' + d) : d;
				let h = date.getHours();
				h = h < 10 ? ('0' + h) : h;
				let m = date.getMinutes();
				m = m < 10 ? ('0' + m) : m;
				let s = date.getSeconds();
				s = s < 10 ? ('0' + s) : s;
				return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
			},
			scrolltoupper() {
				console.log('出顶');
			},
			scroll(e) {
				console.log(e);
			},
			scrolltolower() {
				this.newsshow = false
				console.log("触底");
			},
			ceshi() {
				this.newsshow = false
				this.goToBottom()
				// console.log(this.height);
				// const scrvId = ".scroll-view"
				// const query = wx.createSelectorQuery().in(this)
				// query.select(scrvId).scrollOffset()
				// query.exec(function(res){
				//   console.log(res)
				//  console.log( res[0].scrollTop);
				//   if(that.height- res[0].scrollTop>200){
				//       that.newsshow=true
				//   }
				// })
			},
			phones() {
				uni.navigateTo({
					url: '/pages/userSide/phone'
				})
			},
			place() {
        let data = {
          id:this.userid,
          list:this.info.goodWays
        }
        console.log(data)
        var item = JSON.stringify(data)

				uni.navigateTo({
					url: '/pages/userSide/orderDetails?item='+item
				})
			},
			order() {
				uni.navigateTo({
					url: '/pages/myorder/myorder'
				})
			},
			phone() {
				uni.makePhoneCall({
					phoneNumber: '0571-88355657' //仅为示例
				});
			},
			onPulling(e) {
				console.log("onpulling", e);
				if (e.detail.deltaY < 0) return // 防止上滑页面也触发下拉
				this.triggered = true;
			},
			onRefresh() {
				if (this._freshing) return;
				this.page++;
				console.log('eeee');
				if (this.talkList.length != 0) {
					this.getHistoryMsg();
				} else {
					this.ajax.loadText = '暂无信息';
					setTimeout(() => {
						this.ajax.loading = false;
					}, 300);
				}
			},
			onRestore() {
				this.triggered = 'restore'; // 需要重置
			},
			// 获取历史消息
			getHistoryMsg() {
				this.triggered = false;
				if (!this.ajax.flag) {
					return; //
				}

				// 此处用到 ES7 的 async/await 知识，为使代码更加优美。不懂的请自行学习。
				let get = async () => {
					this.hideLoadTips();
					this.ajax.flag = false;
				    await this.joinHistoryMsg();
					let data = this.talkList;
					console.log('----- 模拟数据格式，供参考 -----');
					console.log(data); // 查看请求返回的数据结构

					// 获取待滚动元素选择器，解决插入数据后，滚动条定位时使用
					let selector = '';

					if (this.ajax.page > 1) {
						// 非第一页，则取历史消息数据的第一条信息元素
						selector = `#msg-${this.talkList[0].id}`;
					} else {
						// 第一页，则取当前消息数据的最后一条信息元素
						selector = `#msg-${data[data.length-1].id}`;
					}

					// 数据挂载后执行，不懂的请自行阅读 Vue.js 文档对 Vue.nextTick 函数说明。
					this.$nextTick(() => {
						// 设置当前滚动的位置
						// this.setPageScrollTo(selector);
						this.goToBottom()
						this.hideLoadTips(true);

						if (data.length < this.ajax.rows) {
							// 当前消息数据条数小于请求要求条数时，则无更多消息，不再允许请求。
							// 可在此处编写无更多消息数据时的逻辑
						} else {
							this.ajax.page++;

							// 延迟 200ms ，以保证设置窗口滚动已完成
							setTimeout(() => {
								this.ajax.flag = true;
							}, 200)
						}

					})
				}
				get();
			},
			// 拼接历史记录消息，正式项目可替换为请求历史记录接口
			joinHistoryMsg() {
				let dasta = []
				this.ajax.page = this.ajax.page + 10
				let data = {
					id: this.charId,
					page: this.ajax.page
				}
				chatSlist(data).then(res => {
					console.log(res.data)
					this.talkList = [...res.data,...this.talkList];
				})
			},
			// 设置页面滚动位置
			// setPageScrollTo(selector){
			// 	let view = uni.createSelectorQuery().in(this).select(selector);
			// 	view.boundingClientRect((res) => {
			// 		uni.pageScrollTo({
			// 		    scrollTop:res.top - 30,	// -30 为多显示出大半个消息的高度，示意上面还有信息。
			// 		    duration: 0
			// 		});
			// 	}).exec();
			// },
			// 隐藏加载提示
			hideLoadTips(flag) {
				if (flag) {
					this.ajax.loadText = '历史消息获取成功';
					setTimeout(() => {
						this.ajax.loading = false;
					}, 300);
				} else {
					this.ajax.loading = true;
					this.ajax.loadText = '正在获取历史消息';
				}
			},
			// 发送信息
			sends() {
				let that = this
				console.log('发送');
				if (!that.content) {
					uni.showToast({
						title: '请输入有效的内容',
						icon: 'none'
					})
					return;
				}
				if (that.content.length > 100) {
					uni.showToast({
						title: '请勿刷屏',
						icon: 'none'
					})
					return;
				}
				uni.showLoading({
					title: '正在发送'
				})
				that.socket.emit(that.userid, {
					msg: that.content,
					status:this.status,//发送端
					orderid:null,//订单

				}).then(res => {
					uni.hideLoading();
					let data = {
						"id": new Date().getTime(),
						"content": that.content,
						"type": 1,
						"pic": that.$store.state.userInfo.wxInfo.avatar

					}
					that.talkList.push(data);
					that.$nextTick(() => {
						// 清空内容框中的内容
						that.content = '';
						// uni.pageScrollTo({
						//     scrollTop: 999999,	// 设置一个超大值，以保证滚动条滚动到底部
						//     duration: 0
						// });
						this.goToBottom()
					})

				})

			},
			goToBottom() {
				const query = wx.createSelectorQuery().in(this);
				query.select('.scroll-view').boundingClientRect();
				query.select('.pos').boundingClientRect();
				query.exec(res => {
					const scorllHeight = res[0].height;
					const listHeight = res[1].height;

					this.scrollTop = listHeight - scorllHeight
					console.log(this.scrollTop)
					this.newsshow = false
				});
			},
		}
	}
</script>

<style lang="scss">
	@import "../../lib/global.scss";

	.bott {
		display: flex;
		padding: 20rpx 30rpx;

		.left {
			margin-left: 40rpx;

			.img {
				width: 100rpx;
				height: 100rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				background-color: #F7F8FC;

				image {
					width: 40rpx;
				}
			}

			view {
				text-align: center;
				padding: 10rpx 0 20rpx;
				color: #666;
				font-size: 22rpx;
			}
		}
	}

	.navtop {
		width: 92vw;
		margin: 40rpx auto;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.left {
			position: relative;

			image {
				width: 330rpx;
				height: 110rpx;
			}

			view {
				position: absolute;
				position: absolute;
				right: 60rpx;
				top: 50%;
				transform: translate(0, -50%);
				color: #fff;
			}
		}
	}

	.jia {
		padding: 10rpx;
		background-color: #F4F4F4;
		border-radius: 100rpx;
		text-align: center;
		color: #999;
	}

	page {
		background-color: #F3F3F3;
		font-size: 28rpx;
	}

	/* 加载数据提示 */
	.tips {
		position: absolute;
		left: 0;
		top: var(--window-top);
		width: 100%;
		z-index: 9;
		background-color: rgba(0, 0, 0, 0.15);
		height: 72rpx;
		line-height: 72rpx;
		transform: translateY(-80rpx);
		transition: transform 0.3s ease-in-out 0s;

		&.show {
			transform: translateY(0);
		}
	}

	.box-1 {
		width: 100%;
		height: auto;
		padding-bottom: 100rpx;
		box-sizing: content-box;

		/* 兼容iPhoneX */
		margin-bottom: 0;
		margin-bottom: constant(safe-area-inset-bottom);
		margin-bottom: env(safe-area-inset-bottom);
	}

	.box-2 {
		position: fixed;
		left: 0;
		width: 100%;
		bottom: 0;
		height: auto;
		z-index: 2;
		border-top: #e5e5e5 solid 1px;
		box-sizing: content-box;
		background-color: #fff;
		/* 兼容iPhoneX */
		padding-bottom: 0;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);

		>view {
			padding: 0 20rpx;
			height: 100rpx;
		}

		.content {
			background-color: #fff;
			height: 64rpx;
			padding: 0 20rpx;
			border-radius: 32rpx;
			font-size: 28rpx;
		}

		.send {
			background-color: #1A8AE1;
			color: #fff;
			height: 64rpx;
			margin-left: 20rpx;
			border-radius: 32rpx;
			padding: 0;
			width: 120rpx;
			line-height: 62rpx;

			&:active {
				background-color: #1A8AE1;
			}
		}
	}

	.talk-list {
		padding-bottom: 20rpx;

		/* 消息项，基础类 */
		.item {
			padding: 20rpx 20rpx 0 20rpx;
			align-items: flex-start;
			align-content: flex-start;
			color: #333;

			.pic {
				width: 92rpx;
				height: 92rpx;
				border-radius: 50%;
				border: #fff solid 1px;
			}

			.content {
				padding: 20rpx;
				border-radius: 4px;
				max-width: 500rpx;
				word-break: break-all;
				line-height: 52rpx;
				position: relative;
			}

			/* 收到的消息 */
			&.pull {
				.content {
					margin-left: 32rpx;
					background-color: #F4F4F4;

					&::after {
						content: '';
						display: block;
						width: 0;
						height: 0;
						border-top: 16rpx solid transparent;
						border-bottom: 16rpx solid transparent;
						border-right: 20rpx solid #fff;
						position: absolute;
						top: 30rpx;
						left: -18rpx;
					}
				}
			}

			/* 发出的消息 */
			&.push {
				/* 主轴为水平方向，起点在右端。使不修改DOM结构，也能改变元素排列顺序 */
				flex-direction: row-reverse;

				.content {
					margin-right: 32rpx;
					background-color: #a0e959;

					&::after {
						content: '';
						display: block;
						width: 0;
						height: 0;
						border-top: 16rpx solid transparent;
						border-bottom: 16rpx solid transparent;
						border-left: 20rpx solid #a0e959;
						position: absolute;
						top: 30rpx;
						right: -18rpx;
					}
				}
			}
		}
	}
</style>
